// 接受请求，分发中转到模块
// @system GO-CRAWL <shop-yun.com>
// @version go-crawl 1.0
// @author xiaotangren  <unphp@qq.com>
// @data 2014-07-29
package socket

import (
	"encoding/json"
	"fmt"
	"net"
	conf "shop-yun.go/go-crawl/utils/conf"
	"strconv"
)

//接受请求的数据结构
type SocketParamsJson struct {
	Type   string
	Module string
	Table  string
	Action string
	Data   interface{}
}

//接受请求，分发处理
func socketDoing(conn net.Conn) {
	defer conn.Close()
	leninfo := make([]byte, 10)
	datainfo := make([]byte, 0)
	t := 1
	for {
		if t%2 == 1 {
			get := ""
			_, err := conn.Read(leninfo)
			if err != nil {
				break
			}
			for _, b := range leninfo {
				if b == 0 {
					continue
				}
				get = get + string(b)
			}
			send_len, _ := strconv.Atoi(get)
			datainfo = make([]byte, send_len)
			t = t + 1
		} else {
			get := ""
			_, err := conn.Read(datainfo)
			if err != nil {
				break
			}
			for _, b := range datainfo {
				if b == 0 {
					continue
				}
				get = get + string(b)
			}
			sendsData(conn, get)
			t = t + 1
		}

	}
}

func sendsData(conn net.Conn, get string) {
	params := new(SocketParamsJson)
	fmt.Println(get)
	err2 := json.Unmarshal([]byte(get), params)
	var rsData conf.SendData
	if err2 != nil { //json解析失败
		rsData = conf.SendData{}
		rsData.Code = 0
		rsData.Error = err2.Error()
	} else { //json解析成功
		if models, ok := getModulesRoute(params.Type); ok == nil { //交由模块进行处理
			rsData = models.Route(params.Module, params.Table, params.Action, params.Data)
		} else {
			rsData = conf.SendData{}
			rsData.Code = 0
			rsData.Error = "Error::not this api's type!"
		}
	}
	rsData1, _ := json.Marshal(rsData)
	rs := string(rsData1)
	first := firstLeninfo(conn, rs)
	sendbyte := []byte(rs)
	send := append(first, sendbyte...)
	conn.Write(send)
}

func firstLeninfo(conn net.Conn, str string) []byte {
	minsend := make([]byte, 10)
	first := append([]byte(strconv.Itoa(len(str))), minsend...)
	first = first[0:10]
	return first
}
